package com.java.web.lucene;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DbUtils {

	  static {
				try {
					Class.forName(getDBConfigField("driver"));
				} catch (ClassNotFoundException e) {
					throw new RuntimeException(e);
				}
	       }
	
	/**
	 * 获取一个数据库连接
	 * @return 返回一个数据库连接
	 */
	public static Connection getConn() {
		try {
			return DriverManager.getConnection(getDBConfigField("url"), getDBConfigField("user"), getDBConfigField("password"));
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 释放掉数据库的相关资源
	 * @param rs 结果集
	 * @param stm 语句对象
	 * @param conn 连接对象
	 */
	public static void free(ResultSet rs, Statement stm, Connection conn) {
		if (rs != null)
			try {
				rs.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		
		if (stm != null)
			try {
				stm.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		
		if (conn != null)
			try {
				conn.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
	}
	
	/**
	 * 获取指定配置的值
	 * @param name 配置项的名称
	 * @return 配置项的值
	 */
	private static String getDBConfigField(String name) {
		try {
			Properties prop = new Properties();
			InputStream inStream = DbUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
			prop.load(inStream);
			return prop.getProperty(name);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
